<?php
class PostsController extends AppController {
	
	public $helpers = array('Html', 'Form');
	
	public $name = 'Posts';
	
	public $components = array('Session');
	
	// Actions
	public function index() {	
		// Show all elements
		$this->set('posts', $this->Post->find('all'));
	}
	
	public function view($id = null) {		
		// Set the id to the post object
		$this->Post->id = $id;
		
		// Read the post object properties and show them
		$this->set('post', $this->Post->read());
	}
	
	public function add() {
		// If is an http post method
		if ($this->request->is('post')) {
			
			// Save the incoming information (post object)
			if ($this->Post->save($this->request->data)) {
				// Show a user message
				$this->Session->setFlash('Your post has been saved.');
				
				// Redirect to the index action
				$this->redirect(array('action' => 'index'));
			}
		}
	}
	
	public function edit($id = null) {
		// Set the id to the post object
		$this->Post->id = $id;
		
		// If is an http get method
		if ($this->request->is('get')) {
			// Read the post object properties
			$this->request->data = $this->Post->read();
		} else {
			// Save the incoming information (post object)
			if ($this->Post->save($this->request->data)) {
				// Show a user message
				$this->Session->setFlash('Your post has been updated.');
				
				// Redirect to the index action
				$this->redirect(array('action' => 'index'));
			}
		}
	}
	
	public function delete($id) {
		// If is an http post method
		if (!($this->request->is('post'))) {
			// Throw an error
			throw new MethodNotAllowedException();
		}
		
		// Delete the post object with the given id
		if ($this->Post->delete($id)) {
			// Show a user message
			$this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
			
			// Redirect to the index action
			$this->redirect(array('action' => 'index'));
		}
	}
	
	public function json() {
		// To disable the layout
		$this->layout = null;
		
		// Set the json content to the json object
		$this->set('json', $this->Post->find('all'));
	
		// Call the view
		$this->render('../Elements/json');		
	}
	
	public function sendJson() {
		// To disable the required view
		$this->autoRender = false;
		
		// Check if it is a post
		if ($this->request->is('post')) {		
			// Get the json data
			$json = $this->request->input('json_decode');
			
			// Save the data
			if ($this->Post->save($json->Post)) {
				// Log
				$this->log('JSON saved', 'debug');
			}					
		}
	}
}
